package com.xcdh.trading.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.xdevapi.JsonArray;
import com.xcdh.trading.entity.TransactionData;
import com.xcdh.trading.mapper.TransactionDataMapper;
import com.xcdh.trading.service.TransactionDataService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class TransactionDataServiceImpl extends ServiceImpl<TransactionDataMapper, TransactionData> implements TransactionDataService {
    @Autowired
    private  TransactionDataMapper transactionDataMapper ;

    @Override
    public void syncTransactionData(String date) {
        String url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=10000&sort=symbol&asc=1&node=hs_a";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    JSONArray jsonArray = JSONUtil.parseArray(result);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        TransactionData data = jsonArray.get(i , TransactionData.class);
                        data.setTrDateCode(date);
                        data.setTrDate(DateUtil.formatDate(DateUtil.parse(date)));
                        TransactionData data1 = lambdaQuery()
                                .eq(TransactionData::getTrDateCode, data.getTrDateCode())
                                .eq(TransactionData::getSymbol, data.getSymbol()).one();
                        if(data1 == null){
                            save(data) ;
                        }
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
